import requests
import time
import json
from urllib import parse
import sys, getopt

op_str = "-c 请设置cookie"

'''
取时间
'''


def GetTime(i=1):
    time_time = time.time()
    t = int(time_time) + 86400
    if i == 1:
        return time.strftime('%Y%m%d', time.localtime(t))
    elif i == 2:
        return time.strftime('%Y-%m-%d', time.localtime(t)) + " 23:59:00"
    elif i == 3:
        str_time = time.strftime('%Y-%m-%d', time.localtime(t)) + " 23:59:00"
        timeArray = time.strptime(str_time, "%Y-%m-%d %H:%M:%S")
        timeStamp = int(time.mktime(timeArray))
        t1 = timeStamp - int(time_time)
        return int(t1 / 3600)


'''
将URL中的地址替换为KS3内网地址
'''


def Conversion_URL(task_list):
    ks3_internal = "http://ks3-cn-beijing-internal.ksyun.com/fstv-cdn"
    task_list_new = []
    for task_url in task_list:
        task_url = parse.quote(task_url)
        task_list_new.append(task_url.replace("fstv-cdn.ks3-cn-beijing.ksyun.com", ks3_internal, 1))
    return task_list_new


'''
读取文件转换成对象
ks3-cn-beijing-internal.ksyun.com
'''


def Get_taskDic():
    fs_tesk_name = ['fsygyh', 'fsdbsj', 'fsdsj', 'fslndm',]
    taskDic = {}
    for tesk_name in fs_tesk_name:
        try:
            with open(tesk_name + ".txt", encoding="utf-8") as f:
                f_read = f.read()
                read_split = f_read.split('\n')
                task_urls = Conversion_URL(read_split)
                taskDic[tesk_name] = task_urls
        except FileNotFoundError as fe:
            print('文件不存在： ' + tesk_name, fe)
            continue
        except Exception as e:
            print('打开文件时出现异常： ', e)
            continue
    if taskDic:
        return taskDic


'''
生成轮播任务对象
'''


def Generate_task_json(task_dic):
    task_names = task_dic.keys()
    for task_name in task_names:
        task_body = {
            "Name": "",
            "EndDate": "",
            "UniqName": "fstv",
            "PubDomain": "xmtott.fstvgo.com",
            "App": "live",
            "Preset": "live_test",
            "StreamID": "",
            "SrcInfo": [
                # {
                #     "Path": "http://ks3-cn-beijing-internal.ksyun.com/zhangtest111/1111.mp4",
                #     "Index": 0
                # }
            ],
            "DurationHour": 5
        }
        task_urls = task_dic[task_name]
        task_body['Name'] = GetTime() + task_name + "_0"
        task_body['StreamID'] = task_name + "_0"
        task_body['EndDate'] = GetTime(2)
        for inx, task_url in enumerate(task_urls):
            if task_url.strip() != "":
                task_body['SrcInfo'].append({
                    "Path": task_url,
                    "Index": inx
                })
        task_body['DurationHour'] = GetTime(3)
        task_dic[task_name] = task_body

    return task_dic


'''
发送创建轮播任务的请求
'''


def Sden_creater_task(token, task_dic):
    requests.packages.urllib3.disable_warnings()
    headers = {
        "Accept": "application/json, text/plain, */*",
        "Content-Type": "application/json",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36",
        "Cookie": token
    }
    url = "https://mps.ksyun.com/data/loop"
    task_names = task_dic.keys()
    # print(token)
    for task in task_names:
        task_body = task_dic[task]
        response = requests.post(url=url, data=json.dumps(task_body), headers=headers, verify=False, timeout=3)
        create_info = response.json()
        if response.status_code == 200 and create_info['ErrNum'] == 0:
            print(task_body['Name'] + "  " + create_info['ErrMsg'])
        else:
            print(task_body['Name'] + "任务创建失败！！！ ")
            print(create_info)



def main(argv):
    try:
        opts, args = getopt.getopt(argv, "h c:", ["cookie=", "help"])
        if len(opts) == 0:
            # print(opts)
            # print(len(opts))
            print(op_str)
            return
    except getopt.GetoptError as ge:
        print(op_str, ge)
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-c':
            token = arg
            task_dic_old = Get_taskDic()
            task_dic_new = Generate_task_json(task_dic_old)
            Sden_creater_task(token, task_dic_new)
        elif opt == '-h' or opt == '--help':
            print(op_str)


if __name__ == '__main__':
    main(sys.argv[1:])
